package cn.jy.boot.service;

import cn.jy.boot.mapper.UserMapper;
import cn.jy.boot.pojo.Role;
import cn.jy.boot.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService , UserDetailsPasswordService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询用户 认证
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        User user = userMapper.selectUserByUserName(username);
        if (ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("用户不存在");
        }
        //根据用户id查询对应的角色
        List<Role> roles = userMapper.selectRolesByUserId(user.getId());
        //将角色信息设置给User
        user.setRoles(roles);
        return user;
    }

    /**
     * 根据认证后的用户 更新用户密码
     * @param user
     * @param newPassword
     * @return
     */

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer num = userMapper.updatePassword(user.getUsername(), newPassword);
        if (num==1){
            User user1 = (User) user;
            user1.setPassword(newPassword);
        }
        return user;
    }
}
